package com.example.demo.Controller;

import com.example.demo.Comm.AppVariable;
import com.example.demo.Comm.PasswordUtils;
import com.example.demo.Comm.Resultajax;
import com.example.demo.Model.Userinfo;
import com.example.demo.Model.VO.UserinfoVO;
import com.example.demo.Service.Userservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class Usercontroller {

    @Autowired
    private Userservice userservice;

    @RequestMapping("/reg")
    public Resultajax reg(Userinfo userinfo) {
        if(userinfo == null || !StringUtils.hasLength(userinfo.getUsername())
                || !StringUtils.hasLength(userinfo.getPassword())) {
            return Resultajax.fail(-1,"参数错误");
        }
        userinfo.setPassword(PasswordUtils.encrypt(userinfo.getPassword()));
        int reg = userservice.reg(userinfo);

        return Resultajax.succ(reg);
    }

    @RequestMapping("/login")
    public Resultajax login(UserinfoVO userinfovo, HttpServletRequest httpServletRequest) {
        if(userinfovo == null || !StringUtils.hasLength(userinfovo.getUsername())
                || !StringUtils.hasLength(userinfovo.getPassword())) {
            return Resultajax.fail(-1,"参数错误");
        }
        Userinfo userinfo = userservice.GetUserByName(userinfovo.getUsername());
        if(userinfo == null || userinfo.getId() == 0) {
            return Resultajax.fail(-2,"账号或密码错误");
        }
        if(!PasswordUtils.decrypt(userinfovo.getPassword(),userinfo.getPassword())) {
            return Resultajax.fail(-2,"账号或密码错误");
        }
        HttpSession session = httpServletRequest.getSession();
        session.setAttribute(AppVariable.SESSION_USERINFO_KEY,userinfo);
        return Resultajax.succ(1);
    }

    @RequestMapping("/logout")
    public Resultajax logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute(AppVariable.SESSION_USERINFO_KEY) != null) {
            session.removeAttribute(AppVariable.SESSION_USERINFO_KEY);
            return Resultajax.succ(1);
        }
        return Resultajax.fail(-1,"请先登录");
    }

}
